package com.ruoyi.web.controller.post.controller;

import java.util.List;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.web.controller.post.domain.PostComment;
import com.ruoyi.web.controller.post.service.IPostCommentService;
import com.ruoyi.web.controller.post.service.IPostService;

/**
 * 帖子评论信息操作处理
 * 
 * @author thunderhub
 */
@RestController
@RequestMapping("/post/comment")
public class PostCommentController extends BaseController
{
    @Autowired
    private IPostCommentService postCommentService;
    
    @Autowired
    private IPostService postService;

    /**
     * 获取帖子评论列表
     */
    @PreAuthorize("@ss.hasPermi('post:comment:list')")
    @GetMapping("/list")
    public TableDataInfo list(PostComment postComment)
    {
        startPage();
        List<PostComment> list = postCommentService.selectPostCommentList(postComment);
        return getDataTable(list);
    }
    
    /**
     * 导出帖子评论列表
     */
    @PreAuthorize("@ss.hasPermi('post:comment:export')")
    @Log(title = "帖子评论", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PostComment postComment)
    {
        List<PostComment> list = postCommentService.selectPostCommentList(postComment);
        ExcelUtil<PostComment> util = new ExcelUtil<PostComment>(PostComment.class);
        util.exportExcel(response, list, "评论数据");
    }

    /**
     * 获取帖子评论详细信息
     */
    @PreAuthorize("@ss.hasPermi('post:comment:query')")
    @GetMapping(value = "/{commentId}")
    public AjaxResult getInfo(@PathVariable Long commentId)
    {
        return success(postCommentService.selectPostCommentById(commentId));
    }

    /**
     * 新增帖子评论
     */
    @PreAuthorize("@ss.hasPermi('post:comment:add')")
    @Log(title = "帖子评论", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody PostComment postComment)
    {
        postComment.setCreateBy(getUsername());
        postComment.setUserId(getUserId());
        postComment.setUserName(getUsername());
        postComment.setLikes(0L);
        
        // 如果父评论ID为空，设置为0（顶级评论）
        if (postComment.getParentId() == null) {
            postComment.setParentId(0L);
        }
        
        int result = postCommentService.insertPostComment(postComment);
        
        if (result > 0) {
            // 更新帖子评论数
            postService.updatePostComments(postComment.getPostId(), 1);
        }
        
        return toAjax(result);
    }

    /**
     * 修改帖子评论
     */
    @PreAuthorize("@ss.hasPermi('post:comment:edit')")
    @Log(title = "帖子评论", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody PostComment postComment)
    {
        postComment.setUpdateBy(getUsername());
        return toAjax(postCommentService.updatePostComment(postComment));
    }

    /**
     * 删除帖子评论
     */
    @PreAuthorize("@ss.hasPermi('post:comment:remove')")
    @Log(title = "帖子评论", businessType = BusinessType.DELETE)
    @DeleteMapping("/{commentIds}")
    public AjaxResult remove(@PathVariable Long[] commentIds)
    {
        // 查询评论信息，用于后续更新帖子评论数
        for (Long commentId : commentIds) {
            PostComment comment = postCommentService.selectPostCommentById(commentId);
            if (comment != null) {
                // 计算删除的评论和回复总数
                int count = 1; // 至少有一条评论
                
                // 如果是顶级评论，还需要计算回复数
                if (comment.getParentId() == 0) {
                    List<PostComment> replies = postCommentService.selectCommentsByParentId(commentId);
                    count += replies.size();
                }
                
                // 更新帖子评论数
                postService.updatePostComments(comment.getPostId(), -count);
            }
        }
        
        return toAjax(postCommentService.deletePostCommentByIds(commentIds));
    }
    
    /**
     * 获取帖子的评论列表
     */
    @PreAuthorize("@ss.hasPermi('post:comment:list')")
    @GetMapping("/list/{postId}")
    public AjaxResult listByPostId(@PathVariable Long postId)
    {
        List<PostComment> comments = postCommentService.selectCommentsByPostId(postId, 0);
        return success(comments);
    }
    
    /**
     * 点赞评论
     */
    @PreAuthorize("@ss.hasPermi('post:comment:like')")
    @Log(title = "评论点赞", businessType = BusinessType.UPDATE)
    @PostMapping("/like/{commentId}")
    public AjaxResult like(@PathVariable Long commentId)
    {
        int result = postCommentService.updateCommentLikes(commentId, 1);
        return toAjax(result);
    }
} 